package com.hundsun.aitest.util;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.text.StrSubstitutor;
import org.springframework.stereotype.Component;

import org.yaml.snakeyaml.Yaml;
import org.springframework.core.io.ClassPathResource;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Data
@Component
public class YamlOperationUtils {

    private static Map<String, Object> content;
    private static Map<String, Object> basic;
    private static Map<String, Object> scene;

    public static Map<String, Object> readYaml(String yamlFilePath){
        try {
            ClassPathResource classPathResource = new ClassPathResource(yamlFilePath);
            InputStream input = classPathResource.getInputStream();;
            Yaml yaml = new Yaml();
            content = yaml.load(input);
            log.info("读取YAML文件内容: " + content);
            return content;
        } catch (FileNotFoundException e) {
            log.error("读取YAML文件失败: " + e.getMessage());
            return null;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据yaml文件路径，测试点，接口列表获取prompt问题，拼接prompt问题
     * @param yamlFilePath : 路径
     * @param inputData ： 输入数据
     * @return ： prompt问题
     */
    public static List<String> getPromptQuestion(String yamlFilePath, Map<String, Object> inputData){
        content = readYaml(yamlFilePath);
        basic = (Map<String, Object>) content.get("basic");
        scene = (Map<String, Object>) content.get("scene");
        StrSubstitutor strSubstitutor = new StrSubstitutor(inputData);
        List<String> prompts = (List<String>) scene.get("prompts");
        List<String> promptQuestions = new ArrayList<>();
        prompts.forEach((item)->{
            if (item.contains("${")){
                String unit = strSubstitutor.replace(item);
                // prompts.set(prompts.indexOf(item), unit);
                promptQuestions.add(unit);
            }else {
                promptQuestions.add(item);
            }
        });
        log.info("prompt statement : " + promptQuestions);
        return promptQuestions;
    }
}
